#ifndef __EVENTLOOP_H__ 
#define __EVENTLOOP_H__
#include "Acceptor.hpp"
#include "TcpConnection.hpp"
#include "MutexLock.hpp"
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include <functional>
#include <memory>
#include <vector>
#include <map>
using std::vector;
using std::shared_ptr;
using std::function;
using std::map;


namespace wd{

class TcpConnection;
using Functor = function<void()>;
using TcpConnectionPtr = shared_ptr<TcpConnection>;  //为什么用智能指针，而且是shared_ptr 
using TcpConnectionCallback = function<void(TcpConnectionPtr)>; 

class EventLoop{
public:
    EventLoop(Acceptor &accept);
    ~EventLoop();
    void loop();
    void unloop();
    
    void setAllCallbacks(const TcpConnectionCallback &cb1,const TcpConnectionCallback &cb2, const TcpConnectionCallback &cb3){
        _onConnection = cb1;
        _onMessage = cb2;
        _onClose = cb3;
    }

    void runInLoop(Functor &&);

private:
    void waitEpollFd();
    int createEpollFd();
    void addEpollReadEvent(int);
    void delEpollReadEvent(int);
    void handleNewConnection();
    void handleMessage(int);
    int createEventfd();
    void handleReadEvent();
    void doPendingFunctors();
    void wakeup();
    

private:
    int _epfd;
    int _eventfd;
    vector<struct epoll_event> _evArr;
    Acceptor & _accept;
    map<int, TcpConnectionPtr>  _conns;

    TcpConnectionCallback _onConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
    bool                  _isLooping;
    vector<Functor>       _pendingFunctors;
    MutexLock             _mutex;


};

}// end of namespace wd

#endif

